/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.table;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.google.common.collect.Lists;
import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.table.TableType;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.CommonCheckService;
import com.je.common.base.util.DataBaseUtils;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.model.dd.DictionaryItemVo;
import com.je.meta.rpc.table.MetaTableRpcService;
import com.je.meta.service.common.MetaDevelopLogService;
import com.je.meta.service.dbswitch.service.MetaDataService;
import com.je.meta.service.table.MetaTableColumnService;
import com.je.meta.service.table.MetaTableService;
import com.je.table.vo.TableDataView;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/je/meta/resourceTable/table")
public class ResourceTableController extends AbstractPlatformController {

    private static final String EXCEL_DOWNLOAD_KEY = "excelDownloadKeys";


    @Autowired
    private MetaDevelopLogService developLogService;
    @Autowired
    private MetaTableService tableService;
    @Autowired
    private MetaTableColumnService metaTableColumnService;
    @Autowired
    private Environment environment;
    @Autowired
    private CommonCheckService commonCheckService;
    @Autowired
    private MetaDataService metaDataService;
    @Autowired
    private MetaTableRpcService metaTableRpcService;

    @RequestMapping(value = "/translate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult translate(BaseMethodArgument param, HttpServletRequest request) {
        String sql = getStringParameter(request,"sql");
        String strData = getStringParameter(request,"strData");
        String text = tableService.translate(strData,sql);
        return BaseRespResult.successResult(text);
    }

    /**
     * 删除表之前的校验
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteCheck", method = RequestMethod.POST)
    public BaseRespResult deleteCheck(BaseMethodArgument param, HttpServletRequest request) {
        String tableId = getStringParameter(request,"tableId");
        String result = tableService.deleteCheck(tableId);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

    @RequestMapping(value = "/getHomePageInfo", method = RequestMethod.POST)
    public BaseRespResult getHomePageInfo(BaseMethodArgument param, HttpServletRequest request) {
        Map<String,Object> result = tableService.getHomePageInfo();
        return BaseRespResult.successResult(result);
    }

    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/saveFuncAndMenu", method = RequestMethod.POST)
    public BaseRespResult saveFuncAndMenu(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        dynaBean.setStr("JE_CORE_RESOURCETABLE_ID",getStringParameter(request,"JE_CORE_RESOURCETABLE_ID"));
        dynaBean.setStr("FUNCINFO_SY_PARENT",getStringParameter(request,"FUNCINFO_SY_PARENT"));
        dynaBean.setStr("CREATE_MENU",getStringParameter(request,"CREATE_MENU"));
        dynaBean.setStr("MENU_MENUNAME",getStringParameter(request,"MENU_MENUNAME"));
        dynaBean.setStr("MENU_FONTICONCLS",getStringParameter(request,"MENU_FONTICONCLS"));
        dynaBean.setStr("MENU_SY_PARENT",getStringParameter(request,"MENU_SY_PARENT"));
        dynaBean.setStr("AUTHORIZATION",getStringParameter(request,"AUTHORIZATION"));
        dynaBean.setStr("MENU_ICON",getStringParameter(request,"MENU_ICON"));
        /**
         * 校验功能编码是否重复
         */
        List<DynaBean> listdb = metaService.select(dynaBean.getTableCode(),ConditionsWrapper.builder().eq("FUNCINFO_FUNCCODE",dynaBean.getStr("FUNCINFO_FUNCCODE")));
        if(listdb!=null&&listdb.size()>0){
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.code.repeat"));
        }
        DynaBean inserted = tableService.saveFuncAndMenu(dynaBean);
        return BaseRespResult.successResult(inserted,MessageUtils.getMessage("table.funcAndMenu.create.succeed"));
    }


    /**
     * 添加表操作 (普通表，树形表)
     *
     * @param param
     * @param request
     * @return
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doSave", method = RequestMethod.POST)
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String parentId = getStringParameter(request, "SY_PARENT");
        String resourcetableTablename = getStringParameter(request, "RESOURCETABLE_TABLENAME");
        String resourcetableTablecode = getStringParameter(request, "RESOURCETABLE_TABLECODE");
        String resourcetableType = getStringParameter(request, "RESOURCETABLE_TYPE");
        String resourcetableMoreroot = getStringParameter(request, "RESOURCETABLE_MOREROOT");
        String resourcetableIcon = getStringParameter(request, "RESOURCETABLE_ICON");
        String productId = getStringParameter(request, "SY_PRODUCT_ID");
        String tableType = tableService.getTableType(parentId);
        if (StringUtil.isEmpty(productId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("framework.product.id.notEmpty"));
        }
        if (StringUtil.isEmpty(tableType)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.module.canotempty"));
        }
        if (!(TableType.MODULETABLE.equals(tableType))) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.onlyModule"));
        }
        if (StringUtil.isEmpty(resourcetableTablename)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.name.canotEmpty"));
        }
        if (StringUtil.isEmpty(resourcetableTablecode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.canotEmpty"));
        }
        if (StringUtil.isEmpty(resourcetableType)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.type.illegal"));
        }
        if (StringUtil.isEmpty(resourcetableMoreroot)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.tree.singleOrMulti"));
        }
        if (StringUtil.isEmpty(resourcetableIcon)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.icon.notEmpty"));
        }
        boolean matches = resourcetableTablecode.matches("^[A-Z]{1}[A-Z_0-9]{0,100}$");
        if (!matches) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.regrex.message"));
        }
        if (tableService.checkTableCodeExcludeCode(dynaBean)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.repeat"));
        }
        dynaBean.set("RESOURCETABLE_TABLENAME", resourcetableTablename.replaceAll(" ", ""));
        DynaBean inserted = tableService.doSave(dynaBean);
        return BaseRespResult.successResult(inserted,MessageUtils.getMessage("table.saveTable"));
    }

    /**
     * 粘贴表操作
     *
     * @param param
     * @param request
     * @return
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doCopy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doCopy(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String fromTableId = getStringParameter(request, "fromTableId");
        String syParent = getStringParameter(request, "SY_PARENT");
        String isUseNewName = getStringParameter(request, "isUseNewName");
        String newTableCode = getStringParameter(request, "RESOURCETABLE_TABLECODE");
        String newTableName = getStringParameter(request, "RESOURCETABLE_TABLENAME");
        if (StringUtil.isEmpty(fromTableId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.source.notEmpty"));
        }
        if (StringUtil.isEmpty(syParent)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.target.notEmpty"));
        }
        if (StringUtil.isEmpty(newTableCode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.canotEmpty"));
        }
        if (StringUtil.isEmpty(newTableName)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.name.canotEmpty"));
        }
        if (tableService.checkTableCodeExcludeCode(dynaBean)) {
            throw new PlatformException("表编码重复！", PlatformExceptionEnum.JE_CORE_TABLE_CHECKCOLUMN_ERROR);
        }

        dynaBean.set("JE_CORE_RESOURCETABLE_ID", fromTableId);
        dynaBean.set("SY_PARENT", syParent);
        DynaBean pasted = tableService.pasteTable(newTableName, newTableCode, dynaBean, isUseNewName);
        return BaseRespResult.successResult(pasted,MessageUtils.getMessage("table.copy.succeed"));
    }

    /**
     * 应用表
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/apply", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult apply(BaseMethodArgument param, HttpServletRequest request) {
        String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String productId = getStringParameter(request, "SY_PRODUCT_ID");
        if (StringUtil.isEmpty(productId)) {
            return BaseRespResult.errorResult("1000","",MessageUtils.getMessage("framework.product.id.notEmpty"));
        }
        if (StringUtil.isEmpty(resourceId)) {
            return BaseRespResult.errorResult("1000","",MessageUtils.getMessage("table.id.canotEmpty"));
        }
        DynaBean table = tableService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceId);
        if (null == table) {
            return BaseRespResult.errorResult("1000","",MessageUtils.getMessage("table.notExits"));
        }
        String result = DataBaseUtils.checkTableExists(table.getStr("RESOURCETABLE_TABLECODE"));
        if ("1".equals(table.getStr("RESOURCETABLE_ISCREATE"))&&!"0".equals(result)) {
            boolean status = tableService.updateTable(resourceId, true);
            if (status) {
                List<String> list = metaTableRpcService.clearTableCache(table.getStr("RESOURCETABLE_TABLECODE"));
                for (String str : list) {
                    metaService.clearMyBatisTableCache(str);
                }
                return BaseRespResult.successResult("1000","",MessageUtils.getMessage("table.applyUpdate"));
            }
            return BaseRespResult.errorResult("1000","",MessageUtils.getMessage("common.update.error"));
        } else {
            boolean status = tableService.createTable(resourceId);
            if (status) {
                List<String> list = metaTableRpcService.clearTableCache(table.getStr("RESOURCETABLE_TABLECODE"));
                for (String str : list) {
                    metaService.clearMyBatisTableCache(str);
                }
                return BaseRespResult.successResult("1000","",MessageUtils.getMessage("table.applySave"));
            }
            return BaseRespResult.errorResult("1000","",MessageUtils.getMessage("common.save.error"));
        }
    }

    /**
     * 初始化工作流字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/initWfBaseColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initWfBaseColumn(BaseMethodArgument param) throws APIWarnException {
        String pkValue = param.getPkValue();
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        if (table != null) {
            metaTableColumnService.initWfBaseColumns(table);
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 初始化工作流字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/initWfExtendColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initWfExtendColumn(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        if (table != null) {
            try {
                metaTableColumnService.initProcessExtendColumns(table);
            }catch (APIWarnException e){
                return BaseRespResult.errorResult(e.getCode(),e.getMessage());
            }
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 初始化SAAS相关字段
     *
     * @param param
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/initSaasColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initSaasColumn(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        if (table != null) {
            metaTableColumnService.initSaasColumns(table);
        }
        return BaseRespResult.successResult(null, MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 初始化扩展字段
     *
     * @param param
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/initExtendColumns", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initExtendColumns(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        if (table != null) {
            try {
                metaTableColumnService.initExtendColumns(table);
            }catch (APIWarnException e){
                return BaseRespResult.errorResult(e.getCode(),e.getMessage());
            }
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 初始化产品字段
     *
     * @param param
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/initProductColumns", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initProductColumns(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        if (table != null) {
            metaTableColumnService.initProductColumns(table);
        }
        return BaseRespResult.successResult( MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 获取该表的功能信息
     */
    @Deprecated
    @RequestMapping(value = "/getFuncInfoByTable", method = RequestMethod.POST)
    public BaseRespResult getFuncInfoByTable(BaseMethodArgument param) {
        String strData = param.getStrData();
        List<DictionaryItemVo> dicItems = new ArrayList<>();
        if (StringUtil.isNotEmpty(strData)) {
            List<DynaBean> funcInfos = metaService.select("JE_CORE_FUNCINFO",
                    ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME", strData).eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
            for (DynaBean funcInfo : funcInfos) {
                DictionaryItemVo item = new DictionaryItemVo();
                item.setId(funcInfo.getStr("JE_CORE_FUNCINFO_ID"));
                item.setCode(funcInfo.getStr("FUNCINFO_FUNCCODE"));
                item.setText(funcInfo.getStr("FUNCINFO_FUNCNAME"));
                dicItems.add(item);
            }
        }
        return BaseRespResult.successResultPage(dicItems, new Long(dicItems.size()));
    }

    /**
     * 根据功能id获取表信息
     */
    @Deprecated
    @RequestMapping(value = "/getTableInfoByFunc", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getTableInfoByFunc(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", pkValue);
        String tableName = funcInfo.getStr("FUNCINFO_TABLENAME");
        if (StringUtil.isNotEmpty(tableName)) {
            DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().apply("RESOURCETABLE_TABLECODE={0} AND RESOURCETABLE_TYPE in ('PT','TREE','VIEW')", tableName));
            if (table != null) {
                return BaseRespResult.successResult(table);
            } else {
                return BaseRespResult.errorResult(MessageUtils.getMessage("table.notExits"));
            }
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.table.notEmpty"));
        }
    }

    /**
     * 同步资源表字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/syncTableField", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult syncTableField(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = param.getPkValue();
        String ckPkValue = getStringParameter(request, "ckPkValue");
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.sysn.sourceTable.notEmpty"));
        }
        if (StringUtil.isEmpty(ckPkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.sync.targetTable.notEmpty"));
        }
        tableService.syncTableField(pkValue, ckPkValue);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 检查是否有重复得表编码
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/checkTableCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkTableCode(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (tableService.checkTableCodeExcludeCode(dynaBean)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.repeat"));
        } else {
            return BaseRespResult.successResult(MessageUtils.getMessage("table.code.notRepeat"));
        }
    }

    /**
     * 设置主键
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/changeTablePrimaryKey", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult changeTablePrimaryKey(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String newCode = getStringParameter(request, "newCode");
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        if (StringUtil.isEmpty(newCode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("column.code.notEmpty"));
        }
        try {
            String result = tableService.changeTablePrimaryKey(pkValue, newCode);
            if(StringUtil.isNotEmpty(result)){
                return BaseRespResult.errorResult(result);
            }
        }catch (APIWarnException e){
            return BaseRespResult.errorResult(e.getCode(),e.getMessage());
        }
        return BaseRespResult.successResult("",MessageUtils.getMessage("table.change.primaryKey.succes"));
    }

    /**
     * 同步表
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/syncTable", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult syncTable(BaseMethodArgument param, HttpServletRequest request) {
        String resourcetableId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String productId = getStringParameter(request, "SY_PRODUCT_ID");
        if (StringUtil.isEmpty(productId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("framework.product.id.notEmpty"));
        }
        if (StringUtil.isEmpty(resourcetableId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourcetableId);
        if (table == null) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.notExits"));
        }

        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        //同步表的逻辑改成导入表，导入表支持增量修改
        metaDataService.importTable("", tableCode, "", productId);
        table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourcetableId);
        return BaseRespResult.successResult(table);
    }

    /**
     * 构建TreePath
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/syncTreePath", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult syncTreePath(BaseMethodArgument param, HttpServletRequest request) {
        String tableCode = param.getTableCode();
        String preFix = getStringParameter(request, "preFix");
        String pkCode = getStringParameter(request, "pkCode");
        tableService.syncTreePath(tableCode, pkCode, preFix);
        return BaseRespResult.successResult(null, MessageUtils.getMessage("common.operation.success"));
    }

    /**
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/getSqlViewSelect", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getSqlViewSelect(BaseMethodArgument param, HttpServletRequest request) {
        String column = getStringParameter(request, "columns");
        String where = getStringParameter(request, "whereSql");
        String sort = getStringParameter(request, "orderSql");
        String limit = getStringParameter(request, "limit");
        String RESOURCETABLE_TABLECODE = getStringParameter(request, "RESOURCETABLE_TABLECODE");
        String sqlType = getStringParameter(request,"type");
        String sql = tableService.getSqlViewSelect(sqlType,column,where,sort,limit,RESOURCETABLE_TABLECODE);
        return BaseRespResult.successResult(sql);
    }

    /**
     * 导出创建语句及数据插入语句 DDL加载语句
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/showDdl", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult sql(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String type = getStringParameter(request, "type");
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        if (StringUtil.isEmpty(type)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.type.illegal"));
        }
        Map<String, Object> resultMap = new HashMap();
        String sql = tableService.generateSql(pkValue, type);
        resultMap.put("sql", sql);
        return BaseRespResult.successResult(resultMap);
    }

    /**
     * 加载该表的父表和子表信息
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/loadTableData", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadTableData(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        List<TableDataView> datas = new ArrayList<>();
        if (table == null) {
            return BaseRespResult.successResultPage(datas, new Long(datas.size()));
        }
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        if ("0".equals(table.getStr("RESOURCETABLE_ISCREATE")) || "MODULE".equals(table.getStr("RESOURCETABLE_TYPE"))) {
            return BaseRespResult.successResultPage(datas, new Long(datas.size()));
        }
        String parentCodes = table.getStr("RESOURCETABLE_PARENTTABLECODES", "");
        String childCodes = table.getStr("RESOURCETABLE_CHILDTABLECODES", "");
        if (StringUtil.isNotEmpty(parentCodes)) {
            List<DynaBean> parentTables = metaService.select("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().in("RESOURCETABLE_TABLECODE", parentCodes.split(",")));
            for (DynaBean parentTable : parentTables) {
                if (tableCode.equals(parentTable.getStr("RESOURCETABLE_TABLECODE"))) {
                    continue;
                }
                TableDataView tableVo = new TableDataView();
                tableVo.setId(parentTable.getStr("JE_CORE_RESOURCETABLE_ID"));
                tableVo.setTableCode(parentTable.getStr("RESOURCETABLE_TABLECODE"));
                tableVo.setTableName(parentTable.getStr("RESOURCETABLE_TABLENAME"));
                tableVo.setTableType("PARENT");
                datas.add(tableVo);
            }
        }
        if (StringUtil.isNotEmpty(childCodes)) {
            List<DynaBean> childTables = metaService.select("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().in("RESOURCETABLE_TABLECODE", childCodes.split(",")));
            for (DynaBean childTable : childTables) {
                if (tableCode.equals(childTable.getStr("RESOURCETABLE_TABLECODE"))) {
                    continue;
                }
                TableDataView tableVo = new TableDataView();
                tableVo.setId(childTable.getStr("JE_CORE_RESOURCETABLE_ID"));
                tableVo.setTableCode(childTable.getStr("RESOURCETABLE_TABLECODE"));
                tableVo.setTableName(childTable.getStr("RESOURCETABLE_TABLENAME"));
                tableVo.setTableType("CHILD");
                datas.add(tableVo);
            }
        }
        return BaseRespResult.successResultPage(datas, new Long(datas.size()));
    }

    /**
     * 指定sql视图查询操作
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/selectByShowSqlView", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult selectByShowSqlView(BaseMethodArgument param, HttpServletRequest request) {
        String column = getStringParameter(request, "columns");
        String where = getStringParameter(request, "whereSql");
        if(StringUtil.isNotEmpty(where)){
            //达梦的查询条件中，值不能用双引号，否则会被认为是字段
            where = where.replaceAll("\"","'");
        }
        String sort = getStringParameter(request, "orderSql");
        String page = getStringParameter(request, "limit");
        String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");

        String pattern = "^[0-9]*[1-9][0-9]*$";
        if(!Pattern.compile(pattern).matcher(page).matches()){
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.sqlView.limit.canNotEmpty"));
        }
        String[] key = {"SY_PRODUCT_ID", "JE_CORE_RESOURCETABLE_ID"};
        String result = StringUtil.checkEmpty(key, request);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceId);
        if(StringUtil.isNotEmpty(where)||StringUtil.isNotEmpty(sort)){
            if(!commonCheckService.checkSql(dynaBean.getStr("RESOURCETABLE_TABLECODE"),where,sort)){
                return BaseRespResult.errorResult(MessageUtils.getMessage("common.sql.error"));
            }
        }

        List<String> columnList = Arrays.asList(column.split(","));
        List<String> whereList = Arrays.asList(where.split(","));
        List<String> orderList = Arrays.asList(sort.split(","));
        if ("".equals(column)) {
            columnList = new ArrayList<>();
        }
        if ("".equals(where)) {
            whereList = new ArrayList<>();
        }
        if ("".equals(sort)) {
            orderList = new ArrayList<>();
        }
        JSONArray columnArr = JSONArray.parseArray(JSON.toJSONString(columnList));
        JSONArray whereArr = JSONArray.parseArray(JSON.toJSONString(whereList));
        JSONArray orderArr = JSONArray.parseArray(JSON.toJSONString(orderList));

        if("0".equals(dynaBean.getStr("RESOURCETABLE_ISCREATE"))){
           return BaseRespResult.successResultPage(Lists.newArrayList(),0L);
        }

        List<Map<String, Object>> list = tableService.selectSqlTable(columnArr, whereArr, orderArr, dynaBean.getStr("RESOURCETABLE_TABLECODE"), page);
        long total = tableService.selectSqlTableByTotal(whereArr, orderArr, dynaBean.getStr("RESOURCETABLE_TABLECODE"));
        if(list.size() == 0){
            total = 0;
        }
        return BaseRespResult.successResultPage(list,total);
    }

    /**
     * 导出sql视图 TXT
     */
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/exportByShowSqlView", method = RequestMethod.GET)
    public ResponseEntity<InputStream> exportByShowSqlView(BaseMethodArgument param, HttpServletRequest request) {
            String column = getStringParameter(request,"columns");
            String where = getStringParameter(request,"whereSql");
        if(StringUtil.isNotEmpty(where)){
            //达梦的查询条件中，值不能用双引号，否则会被认为是字段
            where = where.replaceAll("\"","'");
        }
            String sort = getStringParameter(request,"orderSql");
            String resourceId =getStringParameter(request,"JE_CORE_RESOURCETABLE_ID");

            List<String> columnList = Arrays.asList(column.split(","));
            List<String> whereList = Arrays.asList(where.split(","));
            List<String> orderList = Arrays.asList(sort.split(","));
            if ("".equals(column)) {
                columnList = new ArrayList<>();
            }
            if ("".equals(where)) {
                whereList = new ArrayList<>();
            }
            if ("".equals(sort)) {
                orderList = new ArrayList<>();
            }
            if (StringUtil.isEmpty(resourceId)) {
                throw new PlatformException(MessageUtils.getMessage("table.id.canotEmpty"), PlatformExceptionEnum.UNKOWN_ERROR);
            }

            JSONArray columnArr = JSONArray.parseArray(JSON.toJSONString(columnList));
            JSONArray whereArr = JSONArray.parseArray(JSON.toJSONString(whereList));
            JSONArray orderArr = JSONArray.parseArray(JSON.toJSONString(orderList));
            boolean status = false;
            if(StringUtil.isEmpty(column)){
                status = true;
            }

            DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceId);
            String tableCode = dynaBean.getStr("RESOURCETABLE_TABLECODE");

            List<Map<String, Object>> list = tableService.selectSqlTable(columnArr, whereArr, orderArr, tableCode, null);
            List<String> insertList = tableService.generateInsertSQL(columnArr, list, tableCode,status);
            if(insertList.size() == 0){
                throw new PlatformException(MessageUtils.getMessage("common.export.cannotEmpty"), PlatformExceptionEnum.UNKOWN_ERROR);
            }

            String fileName = tableCode + "_" + DateUtils.formatDate(new Date()) + ".sql";
            StringBuffer txtDetail = new StringBuffer();
            for (String insertStr : insertList) {
                txtDetail.append(insertStr);
                txtDetail.append("\n");
            }

            InputStream inputStream = new ByteArrayInputStream((txtDetail.toString()).getBytes(StandardCharsets.UTF_8));
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                    .body(inputStream);
    }
}